import Vue from "vue";
import VueRouter from "vue-router";
import {routerPath, LOGIN_TOKEN, SHOPPING_CART, USER_INFO} from "@/common/constant";
import store from "@/store";

Vue.use(VueRouter);

const routes = [
    {
        path: '',
        redirect: routerPath.home
    },
    {
        path: routerPath.home,
        component: () => import('@/views/home/Home')
    },
    {
        path: routerPath.category,
        component: () => import('@/views/category/Category')
    },
    {
        path: routerPath.shoppingCart,
        component: () => import('@/views/shoppingCart/ShoppingCart')
    },
    {
        path: routerPath.profile,
        component: () => import('@/views/profile/Profile')
    },
    {
        path: routerPath.detail + "/:iid",
        component: () => import('@/views/detail/Detail')
    },
    {
        path: routerPath.login,
        component: () => import('@/views/login/Login')
    },
    {
        path: '*',
        component: () => import('@/views/errorPage/NotFound')
    }
]

const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(to) {
    return originalPush.call(this, to).catch(err => err);
}
const originalReplace = VueRouter.prototype.push;
VueRouter.prototype.replace = function replace(to) {
    return originalReplace.call(this, to).catch(err => err);
};

const router = new VueRouter({
    routes,
    mode: 'history',
})

router.beforeEach((to, from, next) => {
    if (to.path === from.path) {
        return;
    }
    if (to.path.includes(routerPath.shoppingCart) && !localStorage.getItem(LOGIN_TOKEN)) {
        next(routerPath.login);
        return;
    }
    next();
})

router.afterEach(() => {
    let userInfo = JSON.parse(localStorage.getItem(USER_INFO));
    if (userInfo) {
        store.dispatch("addAllToShopCart", JSON.parse(localStorage.getItem(SHOPPING_CART + "-" + userInfo.phone)));
    }
})

export default router;